﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Windows.Forms;
using System.Xml;
using DeVierKoeden.Dynamicweb.CreateSite.Extensions;
using DeVierKoeden.Dynamicweb.CreateSite.Models;
using Microsoft.Web.Administration;

namespace DeVierKoeden.Dynamicweb.CreateSite
{
  public static class SiteInfoProvider
  {
    public static List<string> GetUniqueApplicationPaths()
    {
      var sites = GetSiteModels();
      var paths = sites.Select(x => x.GetDynamicwebAppPath()).Distinct();
      return paths.ToList();
    }

    public static List<Site> GetSites()
    {
      var result = new List<Site>();
      using (var iisManager = new ServerManager())
      {
        foreach (var site in iisManager.Sites.OrderBy(x => x.Name))
        {
          if (site.IsDynamicwebSite())
          {
            result.Add(site);
          }
        }
        return result;
      }
    }

    internal static List<DynamicwebSite> GetSiteModels()
    {
      var result = new List<DynamicwebSite>();
      foreach (var site in GetSites())
      {
        try
        {
          string filesFolder = site.GetFilesPath();
          var dwSite = new DynamicwebSite
          {
            Id = site.Id,
            Name = site.Name,
            IsCustom = site.IsCustomSolution(),
            FilesPath = filesFolder,
            AdminPath = site.GetAdminPath(),
            RootPath = site.GetRootPath(),
            AngelLocked = IsAngelLocked(filesFolder),
            SqlSettings = new DynamicwebSite.SqlServerSettings
            {
              Database = site.GetDatabaseName(),
              Instance = site.GetSqlServerInstance(),
              IntegratedSecurity = site.UsesIntegratedSecurity()
            }
          };

          dwSite.SqlSettings.DatabaseVersion = Helpers.GetSqlServerDatabaseVersion(dwSite.SqlSettings.Instance, dwSite.Name);
          dwSite.SqlSettings.Version = Helpers.GetSqlServerVersion(dwSite.SqlSettings.Instance, dwSite.Name);
          result.Add(dwSite);
        }
        catch
        {
          MessageBox.Show(string.Format("Error parsing config for folder: {0}. \r\nMake sure the folder exists and contains a valid GlobalSettings file.", site.GetFilesPath()));
        }
      }
      return result;
    }

    private static bool IsAngelLocked(string filesFolder)
    {
      var value = GetSettingFromDynamicwebGlobalSettings(filesFolder, "/Globalsettings/System/Security/AngelLocked");
      return value != "" && Convert.ToBoolean(value);
    }

    internal static string GetSettingFromDynamicwebGlobalSettings(string filesFolder, string xpath)
    {
      try
      {
        string settingsFile = Path.Combine(filesFolder, "GlobalSettings.config");
        if (!File.Exists(settingsFile))
        {
          settingsFile = Path.Combine(filesFolder, "GlobalSettings.aspx");
        }
        var doc = new XmlDocument();
        doc.Load(settingsFile);
        var node = doc.SelectSingleNode(xpath);
        if (node != null)
        {
          return node.InnerText;
        }
        return "";
      }
      catch (Exception)
      {
        return "";
      }
    }

    public static Site GetSiteById(long id)
    {
      using (var iisManager = new ServerManager())
      {
        var site = iisManager.Sites.FirstOrDefault(x => x.Id == id);
        if (!site.IsDynamicwebSite())
        {
          return null;
        }
        return site;
      }
    }
  }
}
